<template>
	<view class="min-h-screen bg-gray-50 flex items-center justify-center">
		<text class="text-2xl font-bold">扫描二维码即可更换合格证</text>
	</view>
</template>

<script setup>
	import dayjs from "dayjs";
	import {
		useGetScandata
	} from "@/hooks/index.js";
	import useKingdeeIsSuccess from "@/hooks/usekingdeeIsSuccess.ts";
	import {
		kingdeeQuery,
		kingdeeSave,
		kingdeeUnAudit,
	} from "@/network/apis.ts";
	import {
		msg
	} from "@/utils/msg";

	// #ifdef APP-PLUS
	const {
		initListen,
		stopListen
	} = useGetScandata();

	initListen();
	//@ts-ignore
	uni.bus.on("scanCode", (message) => {

		controlKingdee(message);

	});

	onUnload(() => {
		stopListen();
		//@ts-ignore
		uni.bus.off("scanCode");
	});
	// #endif

	// 获取当前时间并且转换格式
	const formatDateTime = (timestamp) => dayjs(timestamp).format("YYMMDDHHmmss");
	// 先通过扫描的条码查入库记录表，更换表中条码，加上更换标识。编辑保存
	const controlKingdee = async (message) => {

		const haveLink = message.indexOf("barcode=");

		const trimmedCode =
			haveLink == -1 ? message : message.split("barcode=")[1];

		console.log(trimmedCode);

		const {
			data: res2
		} = await kingdeeQuery({
			formId: "BPL_InStockUpload",
			fieldKeys: `FID,FEntity_FENTRYID,FBPL_BarCode`,
			filterString: `FBPL_BarCode like '%${trimmedCode}%'`,
		});

		const value = useKingdeeIsSuccess("GET", res2);

		if (value.length == 0) return msg("未找到该条码入库记录");

		const {
			data: materialRes
		} = await kingdeeQuery({
			formId: "BD_MATERIAL",
			fieldKeys: `FName,F_BLU_CPZXBZ.FDataValue as CPZXBZ,FMATERIALID`,
			filterString: `FMATERIALID  = ${trimmedCode.split("|")[3]}`,
		});
		if (materialRes.length == 0)
			return msg("未找到该物料信息，请检查物料信息是否正确！");

		const {
			FName,
			CPZXBZ
		} = materialRes[0];

		const {
			data: auditres
		} = await kingdeeUnAudit({
			formid: "BPL_InStockUpload",
			data: {
				Ids: value[0]["FID"],
			},
		});

		if (!auditres.Result.ResponseStatus.IsSuccess) {
			return useKingdeeIsSuccess("POST", auditres);
		}

		const newCode = trimmedCode.replace(
			trimmedCode.split("|")[7],
			formatDateTime(new Date())
		);
		const {
			data: saveRes
		} = await kingdeeSave({
			formid: "BPL_InStockUpload",
			data: {
				IsAutoSubmitAndAudit: true,
				IsDeleteEntry: false,
				NeedUpDateFields: ["FID", "FEntity", "FBPL_BarCode", "FBPL_Change"],
				Model: {
					FID: value[0]["FID"],
					FEntity: [{
						FEntryID: value[0]["FEntity.FENTRYID"],
						FBPL_BarCode: newCode,
						FBPL_Change: true,
					}, ],
				},
			},
		});

		if (saveRes.Result.ResponseStatus.IsSuccess == true) {
			printText({
				code: newCode,
				FName,
				CPZXBZ,
			});
		} else {
			msg(saveRes.Result.ResponseStatus.Errors[0].Message);
		}

	};

	//入库成功再打印
	const printText = ({
		code,
		FName,
		CPZXBZ
	}) => {
		const contents = [{
				align: "center",
				fontSize: "80",
				type: "TEXT",
				content: "合格证",
			},
			{
				type: "QR",
				align: "center",
				// height: 50,
				content: code,
			},
			{
				align: "left",
				type: "TEXT",
				fontSize: "35",
				content: `产品名称：${FName}`,
			},
			{
				align: "left",
				type: "TEXT",
				fontSize: "35",
				content: `净重：${code.split("|")[5] / 100}KG`,
			},
			{
				align: "left",
				type: "TEXT",
				fontSize: "35",
				content: `执行标准：${CPZXBZ}`,
			},
			{
				align: "left",
				type: "TEXT",
				fontSize: "35",
				content: `生产日期：${code.split("|")[7]}`,
			},
			{
				align: "center",
				type: "TEXT",
				content: "\n\n" + `凯佳食品集团有限公司`,
			},
			{
				align: "center",
				type: "TEXT",
				fontSize: "18",
				content: `地址：临沂市河东区工业园温泉路779号`,
			},
			{
				align: "center",
				type: "TEXT",
				fontSize: "18",
				content: `电话：0539-8389677`,
			},
		];
		// console.log(contents);
		try {
			uni.pda.transactionPrinter({
					contents,
				},
				(res) => {
					if (res.msg === "Transaction print successful!") {
						msg("打印成功");
					}
				},
				(err) => {
					msg("打印失败，请重新打印！");
				}
			);
		} catch (error) {
			uni.showModal({
				title: "提示",
				content: "该设备不支持打印",
			});
		}
	};
</script>

<style>
	/* 可以添加样式 */
</style>